/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.controller.servlet;

import com.context.properties.AplicacionProperties;
import com.context.AppContext;
import com.context.properties.EnahoProperties;
import com.context.conexion.EnahoConexion;
import com.context.properties.ContextProperties;
import com.model.domain.usuario.Perfil;
import com.model.domain.usuario.Usuario;
import com.model.service.UsuarioService;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.quartz.SchedulerException;
import util.www.jdbc.JdbcProperties;
import util.log.MiLoggerFile;
import util.www.jdbc.JdbcUtil;

/**
 *
 * @author Rdelacruz
 */
public class AplicacionServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String clave = request.getParameter("parametro");
        if(clave!=null) {
            if(clave.equals("reset")) {
                try {
                    AppContext.getInstancia().finalizar();
                    response.getWriter().append("Finalizado ");
                    AppContext.getInstancia().inicializar();
                    response.getWriter().append("Inicializado");
                } catch (Exception ex) {
                    throw new ServletException(ex);
                }
            }
            else if(clave.equals("enahoenaho")) {      
                PrintWriter out = response.getWriter();
                try {
                    AplicacionProperties ap = AppContext.getInstancia().getAplicacionProperties();
                    ContextProperties cp = AppContext.getInstancia().getContextProperties();

                    Integer maxConexiones;
                    
                    EnahoProperties ep;
                    Connection con = null;
                    try{
                        con = EnahoConexion.getConexion();
                        ep = AppContext.getInstancia().getEnahoProperties(con); 
                        maxConexiones = JdbcUtil.getMaximoNumeroConexiones(con);
                    }
                    finally {
                        if(con!=null) con.close();
                    }

                    JdbcProperties jp = AppContext.getInstancia().getJdbcProperties();

                    out.println("<!DOCTYPE html>");
                    out.println("<html>");
                    out.println("<head>");
                    out.println("<title>Servlet AplicacionServlet</title>");            
                    out.println("</head>");
                    out.println("<body>");
                    
                    out.println("<h1> Datos del servidor </h1>");
                    out.println("<table border='1'>");            
                    out.println("<tr> <td>Fecha y Hora </td> <td>" + new Date() + "</td> </tr>");
                    out.println("<tr> <td>Max. conexiones </td> <td>" + maxConexiones + "</td> </tr>");
                    out.println("</table>");

                    out.println("<h1> AplicacionProperties </h1>");
                    out.println("<table border='1'>");            
                    out.println("<tr> <td>Version</td> <td>" + ap.getVersion() + "</td> </tr>");
                    out.println("<tr> <td>Ruta de enaho.properties</td> <td>" + ap.getRutaEnahoProperties() + "</td> </tr>");
                    out.println("<tr> <td>Ruta de jdbc.properties</td> <td>" + ap.getRutaJdbcProperties() + "</td> </tr>");
                    out.println("<tr> <td>Ruta de context.properties</td> <td>" + ap.getRutaContextProperties() + "</td> </tr>");
                    out.println("<tr> <td>En produccion</td> <td>" + ap.isEnProduccion() + "</td> </tr>");
                    out.println("</table>");

                    out.println("<h1> EnahoProperties </h1>");
                    out.println("<table border='1'>");            
                    out.println("<tr> <td>A&ntilde;o</td> <td>" + ep.getAnho() + "</td> </tr>");
                    out.println("<tr> <td>Directorio_upload</td> <td>" + ep.getDirectorio_upload() + "</td> </tr>");
                    out.println("<tr> <td>Directorio_upload_copia</td> <td>" + ep.getDirectorio_upload_copia() + "</td> </tr>");
                    out.println("</table>");

                    out.println("<h1> JdbcProperties </h1>");
                    out.println("<table border='1'>");            
                    out.println("<tr> <td>Driver</td> <td>" + jp.getDriver() + "</td></tr>");
                    out.println("<tr> <td>Url</td> <td>" + jp.getUrl() + "</td></tr>");
                    out.println("</table>");

                    out.println("<h1> ContextProperties </h1>");
                    out.println("<table border='1'>");            
                    out.println("<tr> <td>Directorio_log</td> <td>" + cp.getDirectorio_log() + "</td> </tr>");
                    out.println("</table>");

                    MiLoggerFile lc;
                    out.println("<h1> LoggerContext </h1>");
                    out.println("<table border='1'>");
                    lc = AppContext.getInstancia().getLoggerContext().getLoggerCargaAutomatica();                
                    out.println("<tr> <td>Path</td> <td>" + (lc!=null ? lc.getAbsolutePath() : "") + "</td></tr>");
                    lc = AppContext.getInstancia().getLoggerContext().getLoggerErrores();
                    out.println("<tr> <td>Path</td> <td>" + (lc!=null ? lc.getAbsolutePath() : "") + "</td></tr>");
                    lc = AppContext.getInstancia().getLoggerContext().getLoggerRequest();
                    out.println("<tr> <td>Path</td> <td>" + (lc!=null ? lc.getAbsolutePath() : "") + "</td></tr>");
                    out.println("</table>");

                    lc = AppContext.getInstancia().getLoggerContext().getLoggerCargaAutomatica();                
                    if(lc!=null) {
                        File fileLog = lc.getFileLog(); 
                        if(fileLog!=null) {
                            out.println("<h3> LoggerCargaAutomatica </h3>");
                            out.println("<table border='1'>");            
                            out.println("<tr> <td>Path</td> <td>" + fileLog.getPath() + "</td></tr>");
                            out.println("<tr> <td>CanonicalPath</td> <td>" + fileLog.getCanonicalPath() + "</td></tr>");
                            out.println("<tr> <td>AbsolutePath</td> <td>" + fileLog.getAbsolutePath() + "</td></tr>");
                            out.println("<tr> <td>Name</td> <td>" + fileLog.getName() + "</td></tr>");
                            out.println("<tr> <td>Parent</td> <td>" + fileLog.getParent() + "</td></tr>");
                            out.println("</table>");
                        }
                    }
                    out.println("<table border='1'>");


                    UsuarioService service = (UsuarioService)AppContext.getInstancia().getControllerContext().getUsuarioController().getService();
                    List<Usuario> lista = service.findByAll();
                    out.println("<h1> Usuarios </h1>");
                    out.println("<table border='1'>");
                    out.println("<tr> <td>Usuario</td>"
                            + "<td>Nombre</td>"
                            + "<td>Estado</td>"
                            + "<td>Perfil</td>"
                            + "<td>Navegador Web</td>"
                            + "<td>Fecha y Hora de Logueo</td>"
                            + "</tr>");
                    for(Usuario u : lista) {                
                        Perfil p = u.getPerfil();
                        String perfil = p!=null ? p.getCodigo()+" "+p.getNombre() : "";
                        out.println("<tr> "
                                + "<td>"+u.getIdentificador()+"</td>"
                                + "<td>"+u.getPersonal().getNombres()+"</td>"
                                + "<td>"+u.getEstado()+"</td>"
                                + "<td>"+perfil+"</td>"
                                + "<td>"+u.getNavegadorWeb()+"</td>"
                                + "<td>"+u.getFechaLogueo()+"</td>"
                                + "</tr>");
                    }
                    out.println("</table>");

                    out.println("</body>");
                    out.println("</html>");


                    File filePrueba = new File("prueba.txt");                
                    out.println("<h1> Prueba </h1>");
                    out.println("<table border='1'>");            
                    out.println("<tr> <td>Path</td> <td>" + filePrueba.getPath() + "</td></tr>");
                    out.println("<tr> <td>CanonicalPath</td> <td>" + filePrueba.getCanonicalPath() + "</td></tr>");
                    out.println("<tr> <td>AbsolutePath</td> <td>" + filePrueba.getAbsolutePath() + "</td></tr>");
                    out.println("<tr> <td>Name</td> <td>" + filePrueba.getName() + "</td></tr>");
                    out.println("<tr> <td>Parent</td> <td>" + filePrueba.getParent() + "</td></tr>");
                    out.println("</table>");
                } 
                catch (Exception ex) {
                    //throw new ServletException(ex);
                    ex.printStackTrace(response.getWriter());                
                }
                finally {
                    out.close();
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
